package com.cn.algorithm02.class17;

/***
 * @author: hels
 * @description: 特殊图结构转换成点线图结构
 * 假设给定数组matrix[?][3]，每一个元素代表[权重, 起点, 终点]
 * 思路：当前接口实现结构转换，将数组遍历将属性赋给图类
 **/
public class C01_GraphGenerator {
    public static Graph createGraph(Integer[][] matrix) {
        Graph graph = new Graph();
        for (int i = 0; i < matrix.length; i++) {
            Integer weight = matrix[i][0];
            Integer from = matrix[i][1];
            Integer to = matrix[i][2];
            if (!graph.nodes.containsKey(from)) {
                graph.nodes.put(from, new Node(from));
            }
            if (!graph.nodes.containsKey(to)) {
                graph.nodes.put(to, new Node(to));
            }

            Node fromNode = graph.nodes.get(from);
            Node toNode = graph.nodes.get(to);
            Edge edge = new Edge(weight, fromNode, toNode);
            fromNode.nexts.add(toNode);
            fromNode.out++;
            fromNode.edges.add(edge);
            toNode.in++;

            graph.edges.add(edge);
        }

        return graph;
    }
}
